package com.lx.sync.core.service.impl;

import com.lx.sync.common.util.CacheUtil;
import com.lx.sync.core.model.SyncState;
import com.lx.sync.core.service.SyncStateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 默认的同步状态服务实现
 * 使用Redis作为存储，业务系统可以覆盖此实现
 */
@Slf4j
@Service
public class DefaultSyncStateServiceImpl implements SyncStateService {

    private static final String SYNC_STATE_KEY_PREFIX = "sync:state:";
    private static final int CACHE_EXPIRE_DAYS = 7;

    @Autowired
    private CacheUtil cacheUtil;

    @Override
    public SyncState getLatestSyncState(String idxName) {
        String key = SYNC_STATE_KEY_PREFIX + idxName;
        return cacheUtil.get(key, SyncState.class);
    }

    @Override
    public boolean saveSyncState(SyncState syncState) {
        try {
            String key = SYNC_STATE_KEY_PREFIX + syncState.getIdxName();
            cacheUtil.set(key, syncState, CACHE_EXPIRE_DAYS, TimeUnit.DAYS);
            return true;
        } catch (Exception e) {
            log.error("保存同步状态到Redis失败", e);
            return false;
        }
    }

    @Override
    public boolean updateSyncState(SyncState syncState) {
        try {
            String key = SYNC_STATE_KEY_PREFIX + syncState.getIdxName();
            cacheUtil.set(key, syncState, CACHE_EXPIRE_DAYS, TimeUnit.DAYS);
            return true;
        } catch (Exception e) {
            log.error("保存同步状态到Redis失败", e);
            return false;
        }
    }


}
